package com.oracle.lingshangejia.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lws.basic.utils.common.AdapterIntegerDefault0;
import com.lws.basic.utils.common.DoubleDefault0Adapter;
import com.oracle.lingshangejia.Constant;

import com.oracle.lingshangejia.R;
import com.oracle.lingshangejia.adapter.FileListAdapter;
import com.oracle.lingshangejia.base.BaseActivity;
import com.oracle.lingshangejia.bean.ResidentBean;
import com.oracle.lingshangejia.bean.SpecialDiseaseBaen;
import com.oracle.lingshangejia.bean.User;
import com.oracle.lingshangejia.bean.VisitRecordBean;
import com.oracle.lingshangejia.model.OkgoNetwork;
import com.oracle.lingshangejia.utils.MyLogger;
import com.oracle.lingshangejia.utils.MyToast;
import com.oracle.lingshangejia.utils.ObserverOnNext;
import com.oracle.lingshangejia.utils.OkHttpUtils;
import com.oracle.lingshangejia.utils.RxUtils;
import com.oracle.lingshangejia.utils.SpUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.crashreport.CrashReport;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

/**
 * 居民档案
 */
public class ResidentActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView resident_recyclerview;
    private TextView tv_title;
    private ImageButton ib_back;
    private EditText et_resident_search;
    private FileListAdapter fileListAdapter;
    private TagFlowLayout mFlowLayout;
    private ArrayList<String> titlelist=new ArrayList<>();
    private SpecialDiseaseBaen mSpecialDiseaseBaen; //专项病
    private ResidentBean mResidentBean;
    private int mOffset = 0;
    @BindView(R.id.srl)
    SmartRefreshLayout mSrl;


    @Override
    public int intiLayout() {
        return R.layout.activity_resident;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        mSrl.setPrimaryColorsId(R.color.color_main);

        resident_recyclerview=findViewById(R.id.resident_recyclerview);
        tv_title=findViewById(R.id.tv_title);
        et_resident_search=findViewById(R.id.et_resident_search);
        mFlowLayout=findViewById(R.id.tid_flowlayout);
        ib_back=findViewById(R.id.ib_back);
        ib_back.setOnClickListener(this);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        resident_recyclerview.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper. VERTICAL);

        et_resident_search.setFocusable(false);
        et_resident_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ResidentActivity.this, SearchActivity.class);
                startActivity(intent);
            }
        });

        getNetWork();//获取居民
        getSpecialDisease();//获取专项列表
        initRefresh();//初始化上拉刷新下拉加载更多

    }
    private void initRefresh() {
        mSrl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getNetWork();
            }
        });
        mSrl.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                loadmore();
            }
        });
    }

    //获取专项病标签
    private void getSpecialDisease(){
        Observable.create(new ObservableOnSubscribe<SpecialDiseaseBaen>() {
            @Override
            public void subscribe(ObservableEmitter<SpecialDiseaseBaen> emitter) throws Exception {
                Map<Object,Object> map = new HashMap<>();
                map.put("token", User.getToken());
                map.put("mark",1);
                map.put("offset", 0);
                map.put("limit", 20);
                JSONObject jsonObject = new JSONObject(map);
                MyLogger.i(jsonObject.toString());
                Gson gson  = new Gson();
                String json = OkgoNetwork.post(Constant.special_disease_list, jsonObject.toString());
                MyLogger.i(json);
                emitter.onNext(gson.fromJson(json, SpecialDiseaseBaen.class));
            }
        }).compose(RxUtils.io_main()).subscribe(new ObserverOnNext<SpecialDiseaseBaen>() {
            @Override
            public void onNext(SpecialDiseaseBaen bean) {
                if (bean.getData()!=null && bean.getData().getRows().size()>0) {
                    mSpecialDiseaseBaen = bean;
                    for (SpecialDiseaseBaen.DataBean.RowsBean rowsBean:mSpecialDiseaseBaen.getData().getRows()){
                        titlelist.add(rowsBean.getName());
                    }

                    mFlowLayout.setAdapter(new TagAdapter<String>(titlelist)
                    {

                        @Override
                        public View getView(FlowLayout parent, int position, String s) {
                            final LayoutInflater mInflater = LayoutInflater.from(ResidentActivity.this);
                            TextView tv = (TextView) mInflater.inflate(R.layout.tv, mFlowLayout, false);
                            tv.setText(s);
                            return tv;
                        }
                    });

                    mFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
                        @Override
                        public boolean onTagClick(View view, int position, FlowLayout parent) {
                            try {
                                int id = mSpecialDiseaseBaen.getData().getRows().get(position).getId();
                                List<ResidentBean.DataBean> list = new ArrayList<>();
                                if (mResidentBean.getData() != null && mResidentBean.getData().size() > 0) {
                                    for (ResidentBean.DataBean dataBean : mResidentBean.getData()) {
                                        for (ResidentBean.DataBean.ZxbListBean zxbListBean : dataBean.getZxbList()) {
                                            if (id == zxbListBean.getId()) {
                                                list.add(dataBean);
                                                break;
                                            }
                                        }
                                    }
                                }
                                fileListAdapter.addDate(list);

                            } catch (Exception e) {
                                MyToast.show(e.getMessage());
                                CrashReport.postCatchedException(e);
                            }
                            return false;
                        }
                    });

                }else {
                    MyToast.show(bean.getMsg());
                }

            }
        });

    }

    /**
     * 获取居民列表
     */
    private void getNetWork() {
        showLoading();
        mOffset =0;
        int ysid= (int) SpUtils.get(ResidentActivity.this,"ysid",0);
        HashMap<Object,Object> map = new HashMap<>();
        map.put("ysid",ysid);
        map.put("offset", mOffset);
        map.put("limit", 10);
        OkHttpUtils.getNetWork(this, Constant.baseurl+"online/user/getjmList",map,handler);
    }
    @SuppressLint("HandlerLeak")
    private android.os.Handler handler=new android.os.Handler(){
        @Override
        public void handleMessage(Message msg) {
            dismissLoading();
            mSrl.finishRefresh();
            switch (msg.what){
                case 1:
                    try{
                        if (mFlowLayout.getAdapter() != null){
                            mFlowLayout.getAdapter().notifyDataChanged();
                        }
                        String s= (String) msg.obj;
                        MyLogger.showLargeLog(s);
                        Gson gson = new GsonBuilder()
                                .registerTypeAdapter(Integer.class, new AdapterIntegerDefault0())
                                .registerTypeAdapter(int.class, new AdapterIntegerDefault0())
                                .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                                .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                                .create();
                        mResidentBean = gson.fromJson(s,ResidentBean.class);
                        if(mResidentBean.getCode()==0){

                            fileListAdapter=new FileListAdapter(ResidentActivity.this, mResidentBean.getData());
                            //设置adapter
                            resident_recyclerview.setAdapter(fileListAdapter);


                        }else{
                            Toast.makeText(ResidentActivity.this, mResidentBean.getMsg(),Toast.LENGTH_SHORT).show();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
                case 2: //连接上服务器，错误
                    String error= (String) msg.obj;
                    Toast.makeText(ResidentActivity.this,error,Toast.LENGTH_SHORT).show();
                    break;
                case 3:  //没有网络
                    Toast.makeText(ResidentActivity.this,"网络不可用",Toast.LENGTH_SHORT).show();
                    break;
                case 4: //没有连接上服务器
                    Toast.makeText(ResidentActivity.this,"连接服务器失败",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private void loadmore() {
        showLoading();
        mOffset += 10;
        Observable.create(new ObservableOnSubscribe<ResidentBean>() {
            @Override
            public void subscribe(ObservableEmitter<ResidentBean> emitter) throws Exception {
                int ysid= (int) SpUtils.get(ResidentActivity.this,"ysid",0);

                Map<Object, Object> map = new HashMap<>();
                map.put("token", User.getToken());
                map.put("mark", 1);
                map.put("offset", mOffset);
                map.put("limit", 10);
                map.put("ysid",ysid);
                JSONObject jsonObject = new JSONObject(map);
                MyLogger.i(jsonObject.toString());
                Gson gson = new GsonBuilder()
                        .registerTypeAdapter(Integer.class, new AdapterIntegerDefault0())
                        .registerTypeAdapter(int.class, new AdapterIntegerDefault0())
                        .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                        .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                        .create();
                String json = OkgoNetwork.post(Constant.baseurl+"online/user/getjmList", jsonObject.toString());
                MyLogger.i(json);
                emitter.onNext(gson.fromJson(json, ResidentBean.class));

            }
        }).compose(RxUtils.io_main()).subscribe(new ObserverOnNext<ResidentBean>() {
            @Override
            public void onNext(ResidentBean bean) {
                if (bean.getData() !=null && bean.getData().size()>0){
                   mResidentBean.getData().addAll(bean.getData());
                   fileListAdapter.loadmoreDate(bean.getData());
                }else {
                    MyToast.show("没用更多居民了");
                }
                mSrl.finishLoadmore();
                dismissLoading();
            }
        });
    }
    @Override
    public void initData() {
        et_resident_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                /*判断是否是“搜索”键*/
                if(actionId == EditorInfo.IME_ACTION_SEARCH){
                    String key = et_resident_search.getText().toString().trim();
                    if(TextUtils.isEmpty(key)){
                        Toast.makeText(ResidentActivity.this,"请输入您想要搜索的关键字",Toast.LENGTH_SHORT).show();
                        return true;
                    }
                    //  下面就是大家的业务逻辑
                    //searchPoi(key);
                    //  这里记得一定要将键盘隐藏了
                    //hideKeyBoard();
                    return true;
                }
                return false;
            }
        });
    }

    /**
     * 底部弹出框
     */
    private void showBottomDialog(){
        final Dialog dialog = new Dialog(this, R.style.dialog);
        View view_dialog = LayoutInflater.from(this).inflate(
                R.layout.resident_bottom_dialog, null);
        dialog.setContentView(view_dialog);
        Window dialogWindow = dialog.getWindow();
        //设置位置
        dialogWindow.setGravity(Gravity.BOTTOM);
        //设置dialog的宽高属性
        dialogWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
    }
    /**
     * 底部弹出框
     */
    private void showTopDialog(){
        final Dialog dialog = new Dialog(this, R.style.dialog);
        View view_dialog = LayoutInflater.from(this).inflate(
                R.layout.resident_top_dialog, null);
        dialog.setContentView(view_dialog);
        Window dialogWindow = dialog.getWindow();
        //设置位置
        dialogWindow.setGravity(Gravity.TOP);
        //设置dialog的宽高属性
        dialogWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ib_back:
                finish();
                break;
        }
    }
}
